use regex::Regex;
use std::fs;
use walkdir::WalkDir;

use crate::addmod::insert_into_file;

pub fn addtoask() {
    println!("添加推广弹窗!");
    let mut contents =
        fs::read_to_string("outapk/AndroidManifest.xml").expect("读取文件错误！！！");
    contents = contents.replace("\n", "");
    let re = Regex::new(r#" <activity .+ android:name="(.*?)" .+ <action android:name="android.intent.action.MAIN"/>.+<category android:name="android.intent.category.LAUNCHER"/>.+</intent-filter>.+</activity>"#).unwrap();

    if let Some(c) = re.captures_iter(&contents).last() {
        println!("activity --> {}", &c[1]);
        for entry in WalkDir::new("./outapk/smali") {
            let entry = entry.unwrap();
            let mut s = String::new();
            let _ = &c[1].clone_into(&mut s);
            // 遍历文件夹内容 smali

            let newactivity = s.split(".").last().unwrap();

            // if s.starts_with(".") {
            //     if let Some(stripped) = s.strip_prefix(".") {
            //         newactivity = stripped;
            //     }
            // }
            let smalipath = format!("{}.smali", newactivity);
            // println!("{}", smalipath);
            if entry.path().to_str().unwrap().contains(smalipath.as_str()) {
                let activitypath = entry.path();
                println!("{}", activitypath.display());
                let haystack =
                    fs::read_to_string(activitypath).expect("读取Activity 文件错误！！！");
                    let start = Regex::new(r".method public onCreate\(Landroid/os/Bundle;\)V|.method protected onCreate\(Landroid/os/Bundle;\)V|.method public constructor <init>\(\)V").unwrap();
                let end = Regex::new("return-void").unwrap();
                // println!("{:#?}", haystack);
                let a = start.find(&haystack).expect("开头 --->没有匹配到!!!");
                let b = end
                    .find_at(&haystack, a.end())
                    .expect("结尾 --> 没有匹配到!!!");
                // println!("{:#?}", a);
                // println!("{:#?}", b);

                let _ = insert_into_file(
                    activitypath.to_str().unwrap(),
                    b.start().try_into().unwrap(),
                    r#"
    const-string v1, "🍅"
    const/4 v0, 0x1
    invoke-static {p0, v1, v0}, Landroid/widget/Toast;->makeText(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;
    move-result-object v0
    invoke-virtual {v0}, Landroid/widget/Toast;->show()V
    "#,
                );
                // apktoolbuild();
            }
        }
    }
}
